package biz

import (
	"context"
	"time"

	"lianzi_gos/internal/mods/mpweixin/dal"
	"lianzi_gos/internal/mods/mpweixin/schema"
	"lianzi_gos/pkg/errors"
	"lianzi_gos/pkg/util"
)

// 实勘， 带客到访 追踪表
type Record struct {
	Trans     *util.Trans
	RecordDAL *dal.Record
}

// Query records from the data access object based on the provided parameters and options.
func (a *Record) Query(ctx context.Context, params schema.RecordQueryParam) (*schema.RecordQueryResult, error) {
	params.Pagination = false

	result, err := a.RecordDAL.Query(ctx, params, schema.RecordQueryOptions{
		QueryOptions: util.QueryOptions{
			OrderFields: []util.OrderByParam{
				{Field: "created_at", Direction: util.DESC},
			},
		},
	})
	if err != nil {
		return nil, err
	}
	return result, nil
}

// Get the specified record from the data access object.
func (a *Record) Get(ctx context.Context, id string) (*schema.Record, error) {
	record, err := a.RecordDAL.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if record == nil {
		return nil, errors.NotFound("", "Record not found")
	}
	return record, nil
}

// Create a new record in the data access object.
func (a *Record) Create(ctx context.Context, formItem *schema.RecordForm) (*schema.Record, error) {
	record := &schema.Record{
		ID:        util.NewXID(),
		CreatedAt: time.Now(),
	}

	if err := formItem.FillTo(record); err != nil {
		return nil, err
	}

	err := a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.RecordDAL.Create(ctx, record); err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return record, nil
}

// Update the specified record in the data access object.
func (a *Record) Update(ctx context.Context, id string, formItem *schema.RecordForm) error {
	record, err := a.RecordDAL.Get(ctx, id)
	if err != nil {
		return err
	} else if record == nil {
		return errors.NotFound("", "Record not found")
	}

	if err := formItem.FillTo(record); err != nil {
		return err
	}
	record.UpdatedAt = time.Now()

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.RecordDAL.Update(ctx, record); err != nil {
			return err
		}
		return nil
	})
}

// Delete the specified record from the data access object.
func (a *Record) Delete(ctx context.Context, id string) error {
	exists, err := a.RecordDAL.Exists(ctx, id)
	if err != nil {
		return err
	} else if !exists {
		return errors.NotFound("", "Record not found")
	}

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.RecordDAL.Delete(ctx, id); err != nil {
			return err
		}
		return nil
	})
}
